import path from 'node:path';

import { VantResolver } from '@vant/auto-import-resolver';
import legacy from '@vitejs/plugin-legacy';
import vue from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import Autoprefixer from 'autoprefixer';
import PostcssPxtorem from 'postcss-pxtorem';
import type { Config } from 'svgo';
import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { defineConfig, loadEnv } from 'vite';
import eslint from 'vite-plugin-eslint';
import Inspect from 'vite-plugin-inspect';
import removeConsole from 'vite-plugin-remove-console';
import { viteVConsole } from 'vite-plugin-vconsole';
import zipPack from 'vite-plugin-zip-pack';
import svgLoader from 'vite-svg-loader';

const svgoConfig: Config = {
  plugins: [
    {
      name: 'preset-default',
      params: {
        overrides: {
          // customize default plugin options
          inlineStyles: {
            onlyMatchedOnce: false
          },

          // or disable plugins
          removeDoctype: false,
          removeViewBox: false // ViewBox默认不删除
        }
      }
    },
    {
      name: 'removeAttrs',
      params: { attrs: ['svg:width', 'svg:height'] } // 删除指定节点的属性
    },
    'convertStyleToAttrs', // 将样式转换为属性
    'removeStyleElement', // 删除 <style> 元素
    'prefixIds' // 用文件名或其他任意字符串作为元素 ID 和类名的前缀。
  ]
};

// https://vite.dev/config/
export default defineConfig(({ mode, command }) => {
  const env = loadEnv(mode, process.cwd());
  const { VITE_APP_BASE, VITE_APP_BASE_URL, VITE_APP_PROXY_URL } = env;

  const outDir = VITE_APP_BASE.replaceAll('/', '') || 'dist';

  return {
    base: VITE_APP_BASE,
    resolve: {
      // https://cn.vitejs.dev/config/#resolve-alias
      alias: {
        // 设置路径
        '~': path.resolve(__dirname, './'),
        // 设置别名
        '@': path.resolve(__dirname, './src')
      },
      // https://cn.vitejs.dev/config/#resolve-extensions
      extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue']
    },
    server: {
      port: 80,
      host: true,
      open: true,
      proxy: {
        // https://cn.vitejs.dev/config/#server-proxy
        [`^${VITE_APP_BASE_URL}`]: {
          target: VITE_APP_PROXY_URL,
          changeOrigin: true
          // rewrite: p => p.replace(new RegExp(`^${VITE_APP_BASE_URL}`), '')
        }
      }
    },
    optimizeDeps: {
      include: ['vue', 'vue-router', 'axios', 'pinia', 'lodash-es']
    },
    css: {
      modules: {
        localsConvention: 'camelCase' // 默认只支持驼峰，修改为同时支持横线和驼峰
      },
      postcss: {
        plugins: [
          Autoprefixer(),
          PostcssPxtorem({ rootValue: 37.5, propList: ['*'] }),
          {
            postcssPlugin: 'internal:charset-removal',
            AtRule: {
              charset: atRule => {
                if (atRule.name === 'charset') {
                  atRule.remove();
                }
              }
            }
          }
        ]
      },
      preprocessorOptions: {
        scss: {
          javascriptEnabled: true,
          additionalData: `@use "@/assets/styles/mixin.scss" as *;@use "@/assets/styles/variables.scss" as *;`
        }
      }
    },
    plugins: [
      vue(),
      vueJsx(),
      svgLoader({ svgoConfig }),
      eslint({
        exclude: ['**/node_modules/**', 'dist/**', 'public/**']
      }),
      AutoImport({
        eslintrc: {
          enabled: true
        },
        vueTemplate: true,
        imports: [
          'vue',
          'vue-router',
          'pinia',
          '@vueuse/core',
          {
            axios: [
              // default imports
              ['default', 'axios'] // import { default as axios } from 'axios',
            ]
          }
        ],
        resolvers: [VantResolver()]
      }),
      Components({
        dts: true,
        resolvers: [VantResolver()]
      }),
      removeConsole(),
      command === 'build' && legacy(),
      Inspect(),
      viteVConsole({
        entry: [path.resolve('src/main.ts')],
        enabled: command === 'build' && mode !== 'stage',
        config: {
          maxLogNumber: 1000,
          theme: 'dark'
        }
      }),
      zipPack({
        inDir: outDir,
        outFileName: (() => {
          // eslint-disable-next-line prefer-regex-literals
          const r = new RegExp(':(\\d+)');
          let prot = '';
          if (r.test(VITE_APP_BASE_URL)) {
            prot = `-${r.exec(VITE_APP_BASE_URL)[1]}`;
          }
          return `${outDir}${prot}.zip`;
        })(),
        pathPrefix: outDir
      })
    ],
    build: {
      outDir,
      rollupOptions: {
        output: {
          manualChunks(id) {
            if (/[\\/]node_modules[\\/]_?dayjs[\\/]/.test(id)) {
              return 'dayjs';
            }
            if (/[\\/]node_modules[\\/]_?lodash(-es)?[\\/]/.test(id)) {
              return 'lodash';
            }
            if (/[\\/]node_modules[\\/]_?@vueuse?[\\/]/.test(id)) {
              return 'vueuse';
            }
          }
        }
      }
    }
  };
});
